package com.briup.xml;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 使用java提供的默认解析器 解析方式DOM 解析xml
 */
public class DomParser {
    public static void main(String[] args) {

        ArrayList<Stu> list = new ArrayList<>();
        //创建工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            //通过工厂对象产生 解析器
            DocumentBuilder builder = factory.newDocumentBuilder();
            //解析器去解析xml文档
            Document doc = builder.parse("02code\\src\\com\\briup\\xml\\file\\class.xml");
            //获取根元素
            Element root = doc.getDocumentElement();
            //获取根节点的子元素
            NodeList stus = root.getElementsByTagName("stu");
            for (int i = 0; i < stus.getLength(); i++) {
                Node item = stus.item(i);
                //获取节点的所有属性
                NamedNodeMap attributes = item.getAttributes();
                //获取指定的属性 通过属性名
                Node idNode = attributes.getNamedItem("id");
                //获取属性的值
                String id = idNode.getNodeValue();
                String name="";
                int  age =0;
                //获取该节点的子节点
                NodeList childNodes = item.getChildNodes();
                for (int j = 0; j < childNodes.getLength(); j++) {
                    Node childNode = childNodes.item(j);
                    //获取子节点的名字
                    String nodeName = childNode.getNodeName();
                    if ("name".equals(nodeName)){
                        //获取节点的文本内容
                         name = childNode.getTextContent();
                    }else if ("age".equals(nodeName)){
                         age = Integer.parseInt(childNode.getTextContent());
                    }
                }
                Stu stu = new Stu(id,name,age);
                list.add(stu);
            }
            System.out.println(list);


        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}
